Monitor and Report the Disk Space  through SCRIPT using PowerShell  or VB

from http://www.youdidwhatwithtsql.com/check-disk-space-with-powershell-2/195

# Issue warning if % free disk space is less 
$percentWarning = 15;
# Get server list
$servers = Get-Content "$Env:USERPROFILE\serverlist.txt";
$datetime = Get-Date -Format "yyyyMMddHHmmss";
 
# Add headers to log file
Add-Content "$Env:USERPROFILE\server disks $datetime.txt" "server,deviceID,size,freespace,percentFree";
 
foreach($server in $servers)
{
	# Get fixed drive info
	$disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3";
 
	foreach($disk in $disks)
	{
		$deviceID = $disk.DeviceID;
		[float]$size = $disk.Size;
		[float]$freespace = $disk.FreeSpace;
 
		$percentFree = [Math]::Round(($freespace / $size) * 100, 2);
		$sizeGB = [Math]::Round($size / 1073741824, 2);
		$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
 
		$colour = "Green";
		if($percentFree -lt $percentWarning)
		{
			$colour = "Red";
		}
		Write-Host -ForegroundColor $colour "$server $deviceID percentage free space = $percentFree";
		Add-Content "$Env:USERPROFILE\server disks $datetime.txt" "$server,$deviceID,$sizeGB,$freeSpaceGB,$percentFree";
	}
}
Some basic info is there http://www.computerperformance.co.uk/powershell/powershell_wmi_disk.htm


March 16th, 2012 7:13pm

Dear All,


We are having environment of more then 200 Production Servers which are Critical  hence we need to Monitor and Report the Disk Space  through SCRIPT using PowerShell  or VB. If any body has already been done , Kindly share it.


Thanks & Regards,
Amit Satam


Free Windows Admin Tool Kit Click here and download it now
March 16th, 2012 10:08pm

from http://www.youdidwhatwithtsql.com/check-disk-space-with-powershell-2/195

# Issue warning if % free disk space is less 
$percentWarning = 15;
# Get server list
$servers = Get-Content "$Env:USERPROFILE\serverlist.txt";
$datetime = Get-Date -Format "yyyyMMddHHmmss";
 
# Add headers to log file
Add-Content "$Env:USERPROFILE\server disks $datetime.txt" "server,deviceID,size,freespace,percentFree";
 
foreach($server in $servers)
{
	# Get fixed drive info
	$disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3";
 
	foreach($disk in $disks)
	{
		$deviceID = $disk.DeviceID;
		[float]$size = $disk.Size;
		[float]$freespace = $disk.FreeSpace;
 
		$percentFree = [Math]::Round(($freespace / $size) * 100, 2);
		$sizeGB = [Math]::Round($size / 1073741824, 2);
		$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
 
		$colour = "Green";
		if($percentFree -lt $percentWarning)
		{
			$colour = "Red";
		}
		Write-Host -ForegroundColor $colour "$server $deviceID percentage free space = $percentFree";
		Add-Content "$Env:USERPROFILE\server disks $datetime.txt" "$server,$deviceID,$sizeGB,$freeSpaceGB,$percentFree";
	}
}
Some basic info is there http://www.computerperformance.co.uk/powershell/powershell_wmi_disk.htm


March 16th, 2012 10:13pm

Have a look at this also. It gives a pretty graphical display.

#requires -version 2.0 
#use parameter  drive report to html.ps1 computer1,computer2 or a computer list file 
#change file path and name on line 7 below to reflect name and  path of computer list file using. 
#script will open web browser with current report when completed. 
 
Param ( 
$computers = (Get-Content  "C:\Scripts\Computers.txt") 
) 
 
$Title="Hard Drive Report to HTML" 
 
#embed a stylesheet in the html header 
$head = @" 
<mce:style><!-- 
mce:0 
--></mce:style><style _mce_bogus="1"><!-- 
mce:0 
--></style> 
<Title>$Title</Title> 
<br> 
"@  
 
#define an array for html fragments 
$fragments=@() 
 
#get the drive data 
$data=Get-WmiObject -Class Win32_logicaldisk -filter "drivetype=3" -computer $computers 
 
#group data by computername 
$groups=$Data | Group-Object -Property SystemName 
 
#this is the graph character 
[string]$g=[char]9608  
 
#create html fragments for each computer 
#iterate through each group object 
         
ForEach ($computer in $groups) { 
     
    $fragments+="<H2>$($computer.Name)</H2>" 
     
    #define a collection of drives from the group object 
    $Drives=$computer.group 
     
    #create an html fragment 
    $html=$drives | Select @{Name="Drive";Expression={$_.DeviceID}}, 
    @{Name="SizeGB";Expression={$_.Size/1GB  -as [int]}}, 
    @{Name="UsedGB";Expression={"{0:N2}" -f (($_.Size - $_.Freespace)/1GB) }}, 
    @{Name="FreeGB";Expression={"{0:N2}" -f ($_.FreeSpace/1GB) }}, 
    @{Name="Usage";Expression={ 
      $UsedPer= (($_.Size - $_.Freespace)/$_.Size)*100 
      $UsedGraph=$g * ($UsedPer/2) 
      $FreeGraph=$g* ((100-$UsedPer)/2) 
      #I'm using place holders for the < and > characters 
      "xopenFont color=Redxclose{0}xopen/FontxclosexopenFont Color=Greenxclose{1}xopen/fontxclose" -f $usedGraph,$FreeGraph 
    }} | ConvertTo-Html -Fragment  
     
    #replace the tag place holders. It is a hack but it works. 
    $html=$html -replace "xopen","<" 
    $html=$html -replace "xclose",">" 
     
    #add to fragments 
    $Fragments+=$html 
     
    #insert a return between each computer 
    $fragments+="<br>" 
     
} #foreach computer 
 
#add a footer 
$footer=("<br><I>Report run {0} by {1}\{2}<I>" -f (Get-Date -displayhint date),$env:userdomain,$env:username) 
$fragments+=$footer 
 
#write the result to a file 
ConvertTo-Html -head $head -body $fragments  | Out-File $Path 
 
.\drivereport.htm
Free Windows Admin Tool Kit Click here and download it now
March 16th, 2012 10:44pm

Dear Gandalf,

If I want to Test the above Script in one of the Machine , Do I need to simply execute the the PS Script or any alteration are required in it.


Thanks & Regards,
Amit Satam

March 17th, 2012 3:31am

to run it against one machine type c:\script_path\'hard drive report to html.ps1' computer1 or use a list of computers in a text file with each computer name on a separate line. use 

change line 7   $computers = (Get-Content "C:\Scripts\Computers.txt")    to point to your computer list name and  path

the results will open in your default browser

Free Windows Admin Tool Kit Click here and download it now
March 17th, 2012 5:16am

Hi,

Please also refer to scripting center for the similar scripts:

Disk Space Monitoring - HTML EMAIL Report
http://gallery.technet.microsoft.com/scriptcenter/6e935887-6b30-4654-b977-6f5d289f3a63

Monitor Free Disk Space Information on a Computer
http://gallery.technet.microsoft.com/scriptcenter/04c29c84-5ecc-4bf6-8dd4-2940db63d9f3

List Available Disk Space
http://gallery.technet.microsoft.com/scriptcenter/7fa38863-ad6f-4f46-ac91-9b7d4a30f52b

Disk Space monitoring
http://gallery.technet.microsoft.com/scriptcenter/fd4f5235-1a80-41ed-87e2-189278fd376c

If you encounter any difficulties when customizing the scripts, you may submit a new question in The Official Scripting Guys Forum! which is a best resource for scripting related issues.
 
The Official Scripting Guys Forum!
http://social.technet.microsoft.com/Forums/en/ITCG/threads

Regards,

March 20th, 2012 3:01pm

I'm getting these errors when running this .ps1 file

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument
 that is not null or empty and then try the command again.
At C:\test.ps1:27 char:77
+ $data=Get-WmiObject -Class Win32_logicaldisk -filter "drivetype=3" -computer <<<<  $computers
    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At C:\test.ps1:75 char:56
+ ConvertTo-Html -head $head -body $fragments  | Out-File <<<<  $Path
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileComm

   and

The term '.\drivereport.htm' is not recognized as the name of a cmdlet, function, script file, or operable program. Che
ck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\test.ps1:77 char:18
+ .\drivereport.htm <<<<
    + CategoryInfo          : ObjectNotFound: (.\drivereport.htm:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

  • Proposed as answer by WesleyOlins Thursday, September 06, 2012 10:42 PM
  • Unproposed as answer by WesleyOlins Thursday, September 06, 2012 10:42 PM
Free Windows Admin Tool Kit Click here and download it now
June 27th, 2012 1:24pm

I'm getting these errors when running this .ps1 file

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument
 that is not null or empty and then try the command again.
At C:\test.ps1:27 char:77
+ $data=Get-WmiObject -Class Win32_logicaldisk -filter "drivetype=3" -computer <<<<  $computers
    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At C:\test.ps1:75 char:56
+ ConvertTo-Html -head $head -body $fragments  | Out-File <<<<  $Path
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileComm

   and

The term '.\drivereport.htm' is not recognized as the name of a cmdlet, function, script file, or operable program. Che
ck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\test.ps1:77 char:18
+ .\drivereport.htm <<<<
    + CategoryInfo          : ObjectNotFound: (.\drivereport.htm:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

  • Proposed as answer by WesleyOlins Thursday, September 06, 2012 10:42 PM
  • Unproposed as answer by WesleyOlins Thursday, September 06, 2012 10:42 PM
June 27th, 2012 4:24pm

I'm getting these errors when running this .ps1 file

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument
 that is not null or empty and then try the command again.
At C:\test.ps1:27 char:77
+ $data=Get-WmiObject -Class Win32_logicaldisk -filter "drivetype=3" -computer <<<<  $computers
    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At C:\test.ps1:75 char:56
+ ConvertTo-Html -head $head -body $fragments  | Out-File <<<<  $Path
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileComm

   and

The term '.\drivereport.htm' is not recognized as the name of a cmdlet, function, script file, or operable program. Che
ck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\test.ps1:77 char:18
+ .\drivereport.htm <<<<
    + CategoryInfo          : ObjectNotFound: (.\drivereport.htm:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Try the following to export the results to Excel which will break the numbers up into several columns.

Also, create a list of the server names in a text file and save it to C:\ as Servers.txt

You may also have to set the execution policy if you have not done so.  Open Powershell as Admin and type set-executionpolicy remotesigned

Script taken from: http://community.spiceworks.com/scripts/show/1074-powershell-script-to-check-free-disk-spaces-for-servers

$erroractionpreference = SilentlyContinue 
$a = New-Object -comobject Excel.Application 
$a.visible = $True

$b = $a.Workbooks.Add() 
$c = $b.Worksheets.Item(1)

$c.Cells.Item(1,1) = Machine Name 
$c.Cells.Item(1,2) = Drive 
$c.Cells.Item(1,3) = Total size (GB) 
$c.Cells.Item(1,4) = Free Space (GB) 
$c.Cells.Item(1,5) = Free Space (%) 
$c.cells.item(1,6) = "Name "

$d = $c.UsedRange 
$d.Interior.ColorIndex = 19 
$d.Font.ColorIndex = 11 
$d.Font.Bold = $True 
$d.EntireColumn.AutoFit()

$intRow = 2

$colComputers = get-content "C:\Servers.txt"
foreach ($strComputer in $colComputers) 
{ 
$colDisks = get-wmiobject Win32_LogicalDisk -computername $strComputer -Filter DriveType = 3"
foreach ($objdisk in $colDisks) 
{ 
$c.Cells.Item($intRow, 1) = $strComputer.ToUpper() 
$c.Cells.Item($intRow, 2) = $objDisk.DeviceID 
$c.Cells.Item($intRow, 3) = {0:N0} -f ($objDisk.Size/1GB) 
$c.Cells.Item($intRow, 4) = {0:N0} -f ($objDisk.FreeSpace/1GB) 
$c.Cells.Item($intRow, 5) = {0:P0} -f ([double]$objDisk.FreeSpace/[double]$objDisk.Size) 
$c.cells.item($introw, 6) = $objdisk.volumename

$intRow = $intRow + 1 
} 
}
$d.EntireColumn.AutoFit()
cls

Free Windows Admin Tool Kit Click here and download it now
September 7th, 2012 1:45am

HI, you need to define the output file path.

Example:

#Out put path
$Path = "D:\dp.htm"

October 16th, 2012 6:50am

Dilip...Can you tell us ...how to email the output htm to out mail box.

Thanks
Azam

Free Windows Admin Tool Kit Click here and download it now
December 9th, 2012 12:16pm

Dear you have to use Function sendmail of PowerShell.

refer the below example if the script. this is ready script you just need to change the below things.

1. server.list (Add the IP and name of the server)

2. Add SMTP IP address

3. replace xxx@test.com with your real email id.

# First lets create a text file, where we will later save the freedisk space info
$freeSpaceFileName = "FreeSpace.htm"
$serverlist = "Serverlist.txt"
$warning = 30
$critical = 10
New-Item -ItemType file $freeSpaceFileName -Force
# Getting the freespace info using WMI
#Get-WmiObject win32_logicaldisk  | Where-Object {$_.drivetype -eq 3} | format-table DeviceID, VolumeName,status,Size,FreeSpace | Out-File FreeSpace.txt
# Function to write the HTML Header to the file
Function writeHtmlHeader
{
param($fileName)
$date = ( get-date ).ToString('dd/mm/yyyy')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title>All Servers DiskSpace Report</title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName  "<!--"
add-content $fileName  "td {"
add-content $fileName  "font-family: Tahoma;"
add-content $fileName  "font-size: 11px;"
add-content $fileName  "border-top: 1px solid #999999;"
add-content $fileName  "border-right: 1px solid #999999;"
add-content $fileName  "border-bottom: 1px solid #999999;"
add-content $fileName  "border-left: 1px solid #999999;"
add-content $fileName  "padding-top: 0px;"
add-content $fileName  "padding-right: 0px;"
add-content $fileName  "padding-bottom: 0px;"
add-content $fileName  "padding-left: 0px;"
add-content $fileName  "}"
add-content $fileName  "body {"
add-content $fileName  "margin-left: 5px;"
add-content $fileName  "margin-top: 5px;"
add-content $fileName  "margin-right: 0px;"
add-content $fileName  "margin-bottom: 10px;"
add-content $fileName  ""
add-content $fileName  "table {"
add-content $fileName  "border: thin solid #000000;"
add-content $fileName  "}"
add-content $fileName  "-->"
add-content $fileName  "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"

add-content $fileName  "<table width='100%'>"
add-content $fileName  "<tr bgcolor='#CCCCCC'>"
add-content $fileName  "<td colspan='7' height='25' align='center'>"
add-content $fileName  "<font face='tahoma' color='#003399' size='4'><strong>All Servers DiskSpace Report - $date</strong></font>"
add-content $fileName  "</td>"
add-content $fileName  "</tr>"
add-content $fileName  "</table>"

}

# Function to write the HTML Header to the file
Function writeTableHeader
{
param($fileName)

Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>Drive</td>"
Add-Content $fileName "<td width='50%' align='center'>Drive Label</td>"
Add-Content $fileName "<td width='10%' align='center'>Total Capacity(GB)</td>"
Add-Content $fileName "<td width='10%' align='center'>Used Capacity(GB)</td>"
Add-Content $fileName "<td width='10%' align='center'>Free Space(GB)</td>"
Add-Content $fileName "<td width='10%' align='center'>Freespace %</td>"
Add-Content $fileName "</tr>"
}

Function writeHtmlFooter
{
param($fileName)

Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
}

Function writeDiskInfo
{
param($fileName,$devId,$volName,$frSpace,$totSpace)
$totSpace=[math]::Round(($totSpace/1073741824),2)
$frSpace=[Math]::Round(($frSpace/1073741824),2)
$usedSpace = $totSpace - $frspace
$usedSpace=[Math]::Round($usedSpace,2)
$freePercent = ($frspace/$totSpace)*100
$freePercent = [Math]::Round($freePercent,0)
 if ($freePercent -gt $warning)
 {
 Add-Content $fileName "<tr>"
 Add-Content $fileName "<td>$devid</td>"
 Add-Content $fileName "<td>$volName</td>"

 Add-Content $fileName "<td>$totSpace</td>"
 Add-Content $fileName "<td>$usedSpace</td>"
 Add-Content $fileName "<td>$frSpace</td>"
 Add-Content $fileName "<td>$freePercent</td>"
 Add-Content $fileName "</tr>"
 }
 elseif ($freePercent -le $critical)
 {
 Add-Content $fileName "<tr>"
 Add-Content $fileName "<td>$devid</td>"
 Add-Content $fileName "<td>$volName</td>"
 Add-Content $fileName "<td>$totSpace</td>"
 Add-Content $fileName "<td>$usedSpace</td>"
 Add-Content $fileName "<td>$frSpace</td>"
 Add-Content $fileName "<td bgcolor='#FF0000' align=center>$freePercent</td>"
 #<td bgcolor='#FF0000' align=center>
 Add-Content $fileName "</tr>"
 }
 else
 {
 Add-Content $fileName "<tr>"
 Add-Content $fileName "<td>$devid</td>"
 Add-Content $fileName "<td>$volName</td>"
 Add-Content $fileName "<td>$totSpace</td>"
 Add-Content $fileName "<td>$usedSpace</td>"
 Add-Content $fileName "<td>$frSpace</td>"
 Add-Content $fileName "<td bgcolor='#FBB917' align=center>$freePercent</td>"
 # #FBB917
 Add-Content $fileName "</tr>"
 }
}
Function sendEmail
{ param($from,$to,$subject,$smtphost,$htmlFileName)
$from=New-Object System.Net.Mail.MailAddress "xxx@test.com"
$to= New-Object System.Net.Mail.MailAddress "xxx@test.com"
$subject="Servers Disk space report - $Date" 
$smtphost="X.X.X.X"
$body = Get-Content $htmlFileName
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
$msg.isBodyhtml = $true
$smtp.send($msg)

}

writeHtmlHeader $freeSpaceFileName
foreach ($server in Get-Content $serverlist)
{
 Add-Content $freeSpaceFileName "<table width='100%'><tbody>"
 Add-Content $freeSpaceFileName "<tr bgcolor='#CCCCCC'>"
 Add-Content $freeSpaceFileName "<td width='100%' align='center' colSpan=6><font face='tahoma' color='#003399' size='2'><strong> $server </strong></font></td>"
 Add-Content $freeSpaceFileName "</tr>"

 writeTableHeader $freeSpaceFileName

 $dp = Get-WmiObject win32_logicaldisk -ComputerName $server |  Where-Object {$_.drivetype -eq 3}
 foreach ($item in $dp)
 {
 Write-Host  $item.DeviceID  $item.VolumeName $item.FreeSpace $item.Size
 writeDiskInfo $freeSpaceFileName $item.DeviceID $item.VolumeName $item.FreeSpace $item.Size

 }
}
writeHtmlFooter $freeSpaceFileName
$date = ( get-date ).ToString('yyyy/MM/dd')
sendEmail xxx@test.com xxx@test.com "Disk Space Report - $Date" hub1 $freeSpaceFileName

January 2nd, 2013 12:14pm

Dilip,

If i am just interested in the servers drives which has croosed the TH leve i.e in this case $critical = 10.

I should only receive email with the servers whose drive space has reached the critical level.

Curious to know ...how to tweak like this.

Thanks in Advance.


Free Windows Admin Tool Kit Click here and download it now
January 7th, 2013 11:33am

you can attach a task to event log 2013, source SRV, which is logged when a disk is near capacity.

Log name: System

Source: Srv

EventID:  2013

January 8th, 2013 11:30am

Dilip,

If i am just interested in the servers drives which has croosed the TH leve i.e in this case $critical = 10.

I should only receive email with the servers whose drive space has reached the critical level.

Curious to know ...how to tweak like this.

Thanks in Advance.

I would also like to know this, I only like to get notified if a server is less than % level.

Free Windows Admin Tool Kit Click here and download it now
March 26th, 2013 8:15pm

Hi,

Ive tryed to use your code but i have some problems, from what i see your code is writen for a domain, so that the executer of this Code doenst have restrictions to get the informations for the Given PC, i have 10PCs and i want to monitor their free space but i always get this "HRESULT: 0x80070005 (E_ACCESSDENIED)" when i execute it on each PC with localhost it works, but not on my whole network. So how do i Login indivitualy to each PC?

Thanks for the help.

April 16th, 2013 3:46pm

I'm not seeing anyone using the Get-Volume cmdlet as a basis for this task. Seems like it could be helpful.

[cin-hv3-1]: PS C:\> get-volume

DriveLetter       FileSystemLabel   FileSystem        DriveType         HealthStatus        SizeRemaining             Size
-----------       ---------------   ----------        ---------         ------------        -------------             ----
                  System Reserved   NTFS              Fixed             Healthy                 109.81 MB           350 MB
D                                   NTFS              Removable         Healthy                   3.88 GB          7.47 GB
C                                   NTFS              Fixed             Healthy                   56.5 GB         67.41 GB
E                                                     CD-ROM            Healthy                       0 B              0 B

Free Windows Admin Tool Kit Click here and download it now
May 19th, 2013 9:53pm

I would like to share with you, the same script as above in HTML format..but for memory!!!

$freeSpaceFileName = "C:\CD\RAM5_Usage.htm"

$serverlist = "C:\CD\computers.txt"

 

# Lets create our variables

 $warning = 75

$critical = 85

$noworries = 74.99

  

# Function to write the HTML Header to the file

Function writeHtmlHeader

{

param($fileName)

$date = ( get-date ).ToString('yyyy/MM/dd')

Add-Content $fileName "<html>"

Add-Content $fileName "<head>"

Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"

Add-Content $fileName '<title>Servers_Ram_Utilisation</title>'

add-content $fileName '<STYLE TYPE="text/css">'

add-content $fileName  "<!--"

add-content $fileName  "td {"

add-content $fileName  "font-family: Tahoma;"

add-content $fileName  "font-size: 11px;"

add-content $fileName  "border-"

add-content $fileName  "border-right: 1px solid #999999;"

add-content $fileName  "border-bottom: 1px solid #999999;"

add-content $fileName  "border-"

add-content $fileName  "padding-"

add-content $fileName  "padding-right: 0px;"

add-content $fileName  "padding-bottom: 0px;"

add-content $fileName  "padding-"

add-content $fileName  "}"

add-content $fileName  "body {"

add-content $fileName  "margin-"

add-content $fileName  "margin-"

add-content $fileName  "margin-right: 0px;"

add-content $fileName  "margin-bottom: 10px;"

add-content $fileName  ""

add-content $fileName  "table {"

add-content $fileName  "border: thin solid #000000;"

add-content $fileName  "}"

add-content $fileName  "-->"

add-content $fileName  "</style>"

Add-Content $fileName "</head>"

Add-Content $fileName "<body>"

 

add-content $fileName  "<table width='100%'>"

add-content $fileName  "<tr bgcolor='#CCCCCC'>"

add-content $fileName  "<td colspan='7' height='25' align='center'>"

add-content $fileName  "<font face='tahoma' color='#003399' size='4'><strong>RAM Report - $date</strong></font>"

add-content $fileName  "</td>"

add-content $fileName  "</tr>"

 

}

 

# Function to write the HTML Footer to the file

Function writeHtmlFooter

{

param($fileName)

#Add-Content $fileName "</table>"

Add-Content $fileName "</body>"

Add-Content $fileName "</html>"

}

 

 

# Function to write the HTML Header to the file

Function writeTableHeader

{

param($fileName)

 

 

Add-Content $fileName "<tr bgcolor=#CCCCCC>"

Add-Content $fileName "<td width='10%' align='center'>Server Name</td>"

Add-Content $fileName "<td width='10%' align='center'>Total Visible Memory GB</td>"

Add-Content $fileName "<td width='10%' align='center'>Free Physical Memory GB</td>"

Add-Content $fileName "<td width='10%' align='center'>Memory Usage GB</td>"

Add-Content $fileName "<td width='10%' align='center'>Memory Used %</td>"

Add-Content $fileName "</tr>"

}

 

##########################################################################################################

 

 

 

### SCRIPT

remove-item $freeSpaceFileName

writeHtmlHeader $freeSpaceFileName

writeHtmlFooter $freeSpaceFileName

writeTableHeader $freeSpaceFileName

 

 

foreach ($computer in Get-Content $serverlist) {

 

 

 

    # Lets get our stats

    # Lets create a re-usable WMI method for CPU stats

   $ProcessorStats = Get-WmiObject win32_processor -computer $computer

   $ComputerCpu = $ProcessorStats.LoadPercentage

   $PercentageUsedMemory = ($UsageMemory * 100) / $TotalMemory

   # Lets create a re-usable WMI method for memory stats

   $OperatingSystem = Get-WmiObject win32_OperatingSystem -computer $computer

   # Lets grab the free memory

   $auxFreeMemory = $OperatingSystem.FreePhysicalMemory /1024/1024

    $FreeMemory = "{0:N2}" -f $auxFreeMemory

      # Lets grab the total memory

   $TotalMemory = $OperatingSystem.TotalVisibleMemorySize /1024/1024

   $FormatTotalMemory = "{0:N2}" -f $TotalMemory

      #Resta de memoria

   $UsageMemory = $TotalMemory - $auxFreeMemory

   $FormatUsageMemory = "{0:N2}" -f $UsageMemory

 

    $PercentageUsedMemory = ($UsageMemory * 100) / $TotalMemory

    $FormatMemoryUsed = "{0:N2}" -f $PercentageUsedMemory

    if ($FormatMemoryUsed -ge $critical)

     {

    

    Add-Content $freeSpaceFileName "<tr>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $computer </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FormatTotalMemory </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FreeMemory </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FormatUsageMemory </td>"

    Add-Content $freeSpaceFileName "<td bgcolor='#FF0000' align=center>$FormatMemoryUsed</td>"

    Add-Content $freeSpaceFileName "</tr>" 

    Add-Content $freeSpaceFileName "</tr>"

    }

    elseif (($FormatMemoryUsed -le $critical) -and ($FormatMemoryUsed -gt $warning))

    {

    

    Add-Content $freeSpaceFileName "<tr>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $computer </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FormatTotalMemory </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FreeMemory </td>"

    Add-Content $freeSpaceFileName "<td width='10%' align='center'> $FormatUsageMemory </td>"

    Add-Content $freeSpaceFileName "<td bgcolor='#FFFF00' align=center>$FormatMemoryUsed</td>"

    Add-Content $freeSpaceFileName "</tr>"

    }

    else

   {

   

    Add-Content $freeSpaceFileName "<tr>"

    Add-Content $freeSpaceFileName "<td width='20%' align='center'> $computer </td>"

    Add-Content $freeSpaceFileName "<td width='20%' align='center'> $FormatTotalMemory </td>"

    Add-Content $freeSpaceFileName "<td width='20%' align='center'> $FreeMemory </td>"

    Add-Content $freeSpaceFileName "<td width='20%' align='center'> $FormatUsageMemory </td>" 

    Add-Content $freeSpaceFileName "<td bgcolor='##00FF00' align=center>$FormatMemoryUsed</td>"

    Add-Content $freeSpaceFileName "</tr>"

     

    

   }

   }

October 15th, 2013 6:36pm

Dear Gandalf,

Its nice but can we display IP address with respect to drive space  instead of hostname in report??

Please reply..


  • Edited by sachin12113 Friday, October 25, 2013 5:13 AM
Free Windows Admin Tool Kit Click here and download it now
October 24th, 2013 9:26pm

Dear Gandalf,

Its nice but can we display IP address with respect to drive space  instead of hostname in report??

Please reply..


  • Edited by sachin12113 Friday, October 25, 2013 5:13 AM
October 25th, 2013 12:26am

Hi,

Ive tryed to use your code but i have some problems, from what i see your code is writen for a domain, so that the executer of this Code doenst have restrictions to get the informations for the Given PC, i have 10PCs and i want to monitor their free space but i always get this "HRESULT: 0x80070005 (E_ACCESSDENIED)" when i execute it on each PC with localhost it works, but not on my whole network. So how do i Login indivitualy to each PC?

Thanks for the help.


Did you ever resolve your issue of accessing non-domain joined PCs with this script?
Free Windows Admin Tool Kit Click here and download it now
January 4th, 2014 5:21am

When i run have error 

PS C:\disk> C:\disk\disk2.ps1





    Directory: C:\disk





Mode                LastWriteTime     Length Name                                                                                                                          

----                -------------     ------ ----                                                                                                                          

-a---         1/15/2014   4:52 PM          0 FreeSpace.htm                                                                                                                 

Get-WmiObject : Invalid namespace 

At C:\disk\disk2.ps1:145 char:21

+  $dp = Get-WmiObject <<<<  win32_logicaldisk -ComputerName $server |  Where-Object {$_.drivetype -eq 3} 

    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException

    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

January 15th, 2014 5:30am

Attempted to divide by zero.
At C:\disk\disk2.ps1:86 char:26
+ $freePercent = ($frspace/ <<<< $totSpace)*100 
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException
 
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\disk\disk2.ps1:145 char:21
+  $dp = Get-WmiObject <<<<  win32_logicaldisk -ComputerName $server |  Where-Object {$_.drivetype -eq 3} 
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
 

Attempted to divide by zero.
At C:\disk\disk2.ps1:86 char:26
+ $freePercent = ($frspace/ <<<< $totSpace)*100 
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException
 
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\disk\disk2.ps1:131 char:11
+ $smtp.send <<<< ($msg) 
    + CategoryInfo          : NotSpecified: (:) [], MethodIn

Free Windows Admin Tool Kit Click here and download it now
January 15th, 2014 5:30am

Great job and thanks for posting.

February 18th, 2014 1:32pm

Here is the another script that can be utilized for this purpose, we are using this in our environment.

http://gallery.technet.microsoft.com/scriptcenter/Disk-Space-and-Threshold-48aa62d5

Free Windows Admin Tool Kit Click here and download it now
April 8th, 2014 12:19am

If someone is interested, I added the following line to the HTML script report to add the percentage free (the line in bold):

#create an html fragment 
    $html=$drives | Select @{Name="Drive";Expression={$_.DeviceID}}, 
    @{Name="SizeGB";Expression={$_.Size/1GB  -as [int]}}, 
    @{Name="UsedGB";Expression={"{0:N2}" -f (($_.Size - $_.Freespace)/1GB) }}, 
    @{Name="FreeGB";Expression={"{0:N2}" -f ($_.FreeSpace/1GB) }}, 
@{Name="PercentageFree";Expression={"{0:N2}" -f [Math]::round((($_.Freespace)/$_.Size)*100) }}
    @{Name="Usage";Expression={ 
      $UsedPer= (($_.Size - $_.Freespace)/$_.Size)*100 
      $UsedGraph=$g * ($UsedPer/2) 
      $FreeGraph=$g* ((100-$UsedPer)/2) 
      #I'm using place holders for the < and > characters 
      "xopenFont color=Redxclose{0}xopen/FontxclosexopenFont Color=Greenxclose{1}xopen/fontxclose" -f $usedGraph,$FreeGraph 
    }} | ConvertTo-Html -Fragment  
     

April 3rd, 2015 3:00pm

Account which used to run this script must have admin access on remote computer.

Free Windows Admin Tool Kit Click here and download it now
August 15th, 2015 5:47am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics